import Vue from 'vue'
import VueRouter from 'vue-router'
// import store from '../store'


Vue.use(VueRouter)


// 解决导航重复点击
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import(/* webpackChunkName: "goods" */ '../views/Goods.vue')
  },
  {
    path: '/order',
    name: 'order',
    component: () => import(/* webpackChunkName: "order" */ '../views/Order.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import(/* webpackChunkName: "free" */ '../views/Free.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import(/* webpackChunkName: "user" */ '../views/User.vue'),
    redirect: '/user/cart',
    children: [
      {
        path: '/user/cart',
        name: 'cart',
        component: () => import(/* webpackChunkName: "detail" */ '../components/user/Cart.vue')
      }
    ],
    // 路由独享守卫
    // beforeEnter: (to, from, next) => {
    //   let token = localStorage.getItem('token');
    //   if (token) {
    //     next()
    //   } else {
    //     store.dispatch('showToast/asyncChangtoastshow', {
    //       show: true,
    //       msg: '请先登陆',
    //       type: 'danger'
    //     });
    //     store.commit('loginshow/changshow', {
    //       show: true
    //     })
    //   }
    // }
  },

  {
    path: '/detail',
    name: 'detail',
    component: () => import(/* webpackChunkName: "detail" */ '../views/details.vue')
  },
  {
    path: '*',
    name: 'err',
    component: () => import(/* webpackChunkName: "err" */ '../components/Error.vue')
  },
  // {
  //   path: '/toto/:id?',//+? 表示可传，也可不传参
  //   name: 'toto',
  //   component: () => import(/* webpackChunkName: "err" */ '../components/Error.vue')
  // },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局导航守卫
router.beforeEach((to, from, next) => {
  if (to.path == '/user') {
    let token = localStorage.getItem('token');
    if (token) {
      next()
    } else {
      store.dispatch('showToast/asyncChangtoastshow', {
        show: true,
        msg: '请先登陆',
        type: 'danger'
      });
      this.$store.commit('loginshow/changshow', {
        show: true
      })
    }
    return;
  }
  next();
})


export default router
